package com.wyp.controller.admin;


import com.wyp.pojo.Apartments;
import com.wyp.service.impl.ApartmentsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin")
public class ApartmentManController {

    @Autowired
    private ApartmentsServiceImpl apartmentsService;

    @GetMapping("/apartment_manage.html")
    public String toapartman(Model model) {
        List<Apartments> apartmentsList = apartmentsService.qureyAllApartment();
        model.addAttribute("apartmentsList", apartmentsList);
        return "admin/apartment/apartment_manage";
    }

    @GetMapping("/apartment_update.html/{id}")
    public String toapartup(Model model,
                            @PathVariable("id") int id) {
        Apartments apartmentup = apartmentsService.qureyApartmentById(id);
        model.addAttribute("apartmentup", apartmentup);
        return "admin/apartment/apartment_update";
    }

    @PostMapping("/apartment_update.html")
    public String apartup(Model model,
                          Apartments apartments) {
        int apartmentupinfo = apartmentsService.updateApartment(apartments);
        return "redirect:/admin/apartment_manage.html";
    }

    @GetMapping("/apartment_add.html")
    public String toapartadd() {
        return "admin/apartment/apartment_add";
    }

    @PostMapping("/apartment_add.html")
    public String apartadd(
            Apartments apartments
    ) {
        int apartmentaddinfo = apartmentsService.addApartment(apartments);
        return "redirect:/admin/apartment_manage.html";
    }

    @RequestMapping("/findAddapart")
    @ResponseBody
    public Map<String, Object> findAddapart(String apartmentname) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        boolean isExist;
        if (apartmentsService.findByapartname(apartmentname) != null) {
            isExist = true;
        } else {
            isExist = false;
        }
        resultMap.put("isExist", isExist);
        return resultMap;
    }

    @RequestMapping("/findUpdateapart")
    @ResponseBody
    public Map<String, Object> findUpapart(
            @RequestParam("apartmentname") String apartmentname,
            @RequestParam("apartmentid") String apartmentid) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        boolean isExist;
        if ((apartmentsService.findByapartname(apartmentname) != null) && (apartmentsService.findByapartname(apartmentname).getApartmentid()!=Integer.valueOf(apartmentid))) {
            isExist = true;
        } else {
            isExist = false;
        }
        resultMap.put("isExist", isExist);
        return resultMap;
    }
}
